<template>
    <div>
      <!-- <canvas id="canvas" width="800" height="600" ></canvas> -->
      <div class="ls_maincont"></div>
      <div class="mainDiv hjm_c">
        <div class="r">
          <div class="stage_c_r main_3 hjm_zhjl_item">
            <div class="t">
              <div class="react">
                <i class="l_up"></i>
                <i class="l_down"></i>
                <i class="r_up"></i>
                <i class="r_down"></i>
                <div class="title">
                  <span   style="font-size: 30px ;color: white;">{{ currentTag === "燃尽风层" ? "燃尽风层" : (currentTag + "层燃烧") }}数据监测</span>
                </div>
              </div>
            </div>
            <div class="d d2" style="flex: 1">
              <div style="
                  display: flex;
                  width: 683px;
                  color: #343434;
                  font-size: 36px;
                  justify-content: space-between;
                  position: absolute;
                ">
                <span style="color: white;">左墙</span>
                <span style="color: white;">右墙</span>
              </div>
              <div style="
                  display: flex;
                  color: #343434;
                  font-size: 36px;
                  position: absolute;
                  top: 100px;
                ">
                <span  style="color: white;">后墙</span>
              </div>
              <div style="
                  display: flex;
                  color: #343434;
                  font-size: 36px;
                  position: absolute;
                  top: 560px;
                ">
                <span style="color: white;">前墙</span>
              </div>
              <div class="hjm_zhjl">
                <div class="l_t l_d">
                  <div class="dengpao"></div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="flags" >{{ currentTag }}1 着火距离: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ currentTag === '燃尽风层' ? '' : `${ distanceMap[1] } mm`}}  </div>
                  </div>
                  <div class="pointer_name" style="font-size: 22px; color: white;"  v-show="isShows">{{ currentTag }}1 燃烧温度: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ distanceMap[1] }}&#8451;   </div>
                  </div>

                  <div class="pentou" v-show="isShow"></div>
                </div>
                <div class="l_t">
                  <div class="pentou" v-show="isShow"></div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="flags" >{{ currentTag }}2 着火距离: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ currentTag === '燃尽风层' ? '' : `${ distanceMap[2] } mm`}}</div>
                  </div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="isShows" >{{ currentTag }}1 燃烧温度: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ distanceMap[2] }}&#8451;  </div>
                  </div>
                  <div class="dengpao"></div>
                </div>
                <div class="l_t r_t">
                  <div class="pentou" v-show="isShow"></div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="flags" >{{ currentTag }}3 着火距离: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ currentTag === '燃尽风层' ? '' : `${ distanceMap[3] } mm`}}</div>
                  </div>
                  <div class="pointer_name" style="font-size: 22px; color: white;"  v-show="isShows">{{ currentTag }}1 燃烧温度: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ distanceMap[3] }} &#8451; </div>
                  </div>
                  <div class="dengpao"></div>
                </div>
                <div class="l_t l_d r_d">
                  <div class="dengpao"></div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="flags" >{{ currentTag }}4 着火距离: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ currentTag === '燃尽风层' ? '' : `${ distanceMap[4] } mm`}}</div>
                  </div>
                  <div class="pointer_name" style="font-size: 22px; color: white;" v-show="isShows" >{{ currentTag }}1 燃烧温度: <div class="pointer_value" style="font-size: 23px; color: white;">
                    {{ distanceMap[4] }} &#8451;  </div>
                  </div>
                  <div class="pentou" v-show="isShow"></div>
                </div>
                <div class="c">
                  <div class="c_1"></div>
                  <div class="c_2" id="huoYanDiv">
                  </div>
                  <div class="c_3">
                    <div class="c_31"><img src="../assets/hjmsft2_1.png" /></div>
                    <div class="c_32"><img src="../assets/hjmsft2_1.png" /></div>
                    <div class="c_33"><img src="../assets/hjmsft2_1.png" /></div>
                    <div class="c_34"><img src="../assets/hjmsft2_1.png" /></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stage_c_r main_3 hjm_ps_item">
            <div class="t">
              <div class="react">
                <i class="l_up"></i>
                <i class="l_down"></i>
                <i class="r_up"></i>
                <i class="r_down"></i>
                <div class="title">
                  <span  style="font-size: 30px ;color: white;">{{ currentTag === "燃尽风层" ? "燃尽风层" : (currentTag + "层燃烧器") }}截面温度场偏烧情况</span>
                </div>
              </div>
            </div>
            <div class="d d2">
              <div class="hjm_ps">
                <div class="text_div">
                  <div class="_t">
                    <span style="color: white;">{{ currentTag }}1</span>
                    <span>左墙</span>
                    <span style="color: white;">{{ currentTag }}2</span>
                  </div>
                  <div class="_m">
                    <span  style="color: white;">前墙</span>
                    <span>后墙</span>
                  </div>
                  <div class="_d">
                    <span style="color: white;">{{ currentTag }}4</span>
                    <span style="color: white;">右墙</span>
                    <span style="color: white;">{{ currentTag }}3</span>
                  </div>
                </div>
                <div class="_c"></div>
              </div>
            </div>
          </div>
          <div class="stage_c_r main_3 hjm_wd_item">
            <div class="t">
              <div class="react">
                <i class="l_up"></i>
                <i class="l_down"></i>
                <i class="r_up"></i>
                <i class="r_down"></i>
                <div class="title">
                  <span  style="font-size: 30px ;color: white;"> {{ currentTag === "燃尽风层" ? "燃尽风层" : (currentTag + "层燃烧器") }}截面温度场分布</span>
                </div>
              </div>
            </div>
            <div class="d d2">
              <div class="hjm_ps hjm_wd">
                <div class="text_div">
                  <div class="_t">
                    <span style="font-size: 30px ;color: white;">{{ currentTag }}2</span>
                    <span style="display: none">后墙</span>
                    <span style="color: white;">{{ currentTag }}3</span>
                  </div>
                  <div class="_m">
                    <span style="display: none">左墙</span>
                    <span style="display: none">右墙</span>
                  </div>
                  <div class="_d">
                    <span style="color: white;">{{ currentTag }}1</span>
                    <span style="display: none">前墙</span>
                    <span style="color: white;">{{ currentTag }}4</span>
                  </div>
                </div>
                <div class="_c" id="_c">
                  <div class="hjm_wd_block"  > 
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="r">
          <div class="d" id="zbf_hjm_btns" v-for="item in dianwei" :key="item.key" >
            <span @click="dianji(item.key)" :class="{ active: currentTag === item.key }" style="font-size: 30px; ">{{ item.value }}</span>
          </div>
        </div>
      </div>
      <div class="stage_t">
        <div class="stage_t_left">  
            <img src="../assets/logins.jpg" alt=""> <span>国能怀安热电有限公司</span>
       </div>
       <div  class="stage_t_zhong">燃烧数字化监测与可视化系统</div>
       <div  class="stage_t_right">
           <img src="../assets/timer.png" alt=""> <span>{{ nowTime }}</span>
       </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from "vue";
  import { formatTime } from "../utils/date.js";
  import { field, floor } from "../api/hjm.js";
  import * as THREE from "three";
  import frame0 from "../assets/huomiao/frame_0.png";
  import frame1 from "../assets/huomiao/frame_1.png";
  import frame2 from "../assets/huomiao/frame_2.png";
  import frame3 from "../assets/huomiao/frame_3.png";
  const nowTime = ref("");
  const currentTag = ref("A") // 当前选中的层级
  onMounted(() => {
    setInterval(() => {
      nowTime.value = formatTime(new Date());
    });
    obj()
    dianji("A")
    createSDScene()
  });
  const isShow = ref(true)
  // 逻辑
  let dianwei = ref([])
  let obj = async () => {
    let res = await floor()
    res.data.forEach((item, index) => {
      if (index === 5) {
        dianwei.value.push({ key: item, value: "SOFA燃尽风层" })
      } else {
        dianwei.value.push({ key: item, value: item + "层燃烧器" })
      }
    })
  }
  const pointer_name = ref('')
 
  let flags=ref(true)
  let isShows=ref(true)
  const distanceMap = reactive({})
  let timer=0
  let dianji = async (item) => {
    console.log(pointer_name);
     clearTimeout(timer)
    currentTag.value = item
    
    if(currentTag.value==="S"){
      flags.value=false
    }else{
      flags.value=true;
    }
    if(currentTag.value==='A' || currentTag.value==="B" || currentTag.value== 'C' || currentTag.value== 'D' || currentTag.value== 'E'){
      isShows.value = false
    }else{
      isShows.value = true
    }
    
    // 修改向后台请求数据时的参数。 燃尽风为"S"
    if (item === "燃尽风层") item = "S"
    if (item === "S"){
      isShow.value = false
    }else{
      isShow.value = true
    }
    // 当是 sofa 层时，燃烧器关闭
    let res = await field(item)
    if (res.status === 200) {
      // 设置着火距离监测面板的值和火焰大小
      res.data.distances.forEach((item, index) => {
        distanceMap[item.parameter[1]] = item.v
        // 调整火焰的大小
        setFireScale(index, item.v / 500, item.v / 800)
      })
      // 设置截面温度场分布面板的值和背景色
     // 设置截面温度场分布面板的值和背景5
     const elArr = document.querySelectorAll("#_c>.hjm_wd_block>span")
      res.data.field66.forEach((value, index) => {
        elArr[index].innerText = value
        // let color = calculateColor(value)
        // elArr[index].style.backgroundColor = calculateColor(value)
         let color = calculateColor(value)
      elArr[index].style.backgroundColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`
      })
    }
      timer = setInterval(() => {
        if (item === "燃尽风") item = "S"
        dianji(item);
    }, 3000);

  }
  
  
  // 依据后台返回的value计算对应的颜色 现在区间范围 0-850 是蓝色 的，851-1150 是黄的，1151 以上是红的
  // function calculateColor(v) {
  //   // 将温度v的范围映射到HSL色调从240（蓝色）到10（红色）
  //   let hue = 0
  //   if (v < 850) {
  //     // 蓝色 230 - 190
  //     hue = (1 - v / 850) * 40 + 190
  //   } else if (v < 1150) {
  //     // 黄色 70 - 20
  //     v = v - 850
  //     hue = (1 - v / 300) * 50 + 20
  //   } else if (v > 1200) {
  //     // 红色 20 - 0
  //     v = v - 1200
  //     hue = (1 - Math.min(v / 850, 2)) * 10;
  //   } 
  //   // 返回HSL颜色字符串
  //   return `hsl(${hue}, 90%, 50%)`;
  // }
  // 依据后台返回的value计算对应的颜色
 function calculateColor(value, gradientStep = 300, min = 800, max = 1800, startColor = [80, 192, 237], endColor = [255, 0, 0]) {
  if (value < min) {
    return startColor;
  } else if (value > max) {
    return endColor;
  } else {
    // 计算相对于颜色范围的百分比
    const percentage = (value - min) / (max - min);
    // 根据百分比在颜色范围内进行线性插值
    const interpolatedColor = startColor.map((startComponent, index) => {
      const endComponent = endColor[index];
      return Math.round(startComponent + percentage * (endComponent - startComponent));
    });

    // 根据 gradientStep 调整颜色深度
    const steps = Math.floor((value - min) / gradientStep);
    for (let i = 0; i < steps; i++) {
      interpolatedColor[0] -= Math.floor((startColor[0] - endColor[0]) / (max - min) * gradientStep);
      interpolatedColor[1] -= Math.floor((startColor[1] - endColor[1]) / (max - min) * gradientStep);
      interpolatedColor[2] -= Math.floor((startColor[2] - endColor[2]) / (max - min) * gradientStep);
    }
    return interpolatedColor;
  }
 }
  

  let group
  let createSDScene = function () {
      // 创建一个场景
      const scene = new THREE.Scene();
      // 创建一个相机
      const camera = new THREE.PerspectiveCamera(50, 414 / 380, 0.1, 10000);
      camera.position.z = 380;
    
      // 创建一个渲染器
      const renderer = new THREE.WebGLRenderer({ alpha: true });
      renderer.setSize(414, 380);
      let canvasEl = document.querySelector('#huoYanDiv > canvas')
      if (canvasEl) {
        canvasEl.parentNode.removeChild(canvasEl);
      }
      document.getElementById("huoYanDiv").appendChild(renderer.domElement);
    
      // 创建火焰
      group = new THREE.Group();
      const textures = [];
      const loader = new THREE.TextureLoader();
      Promise.all([
        new Promise((resolve) => {
          loader.load(frame0, function (texture) {
            textures.push(texture);
            // 创建四个火焰
            const geometry = new THREE.PlaneGeometry(150, 75);
            geometry.translate(150 / 2, 0, 0);
            const material = new THREE.MeshBasicMaterial({ map: texture, transparent: true });
            const plane0 = new THREE.Mesh(geometry, material);
            group.add(plane0);
    
            let unitX = 207;
            let unitY = 190;
    
            const plane1 = plane0.clone();
            plane1.rotation.z = (-Math.PI * 11 / 36) * 3;
            plane1.position.set(unitX - 10, unitY - 26, 0);
            group.add(plane1);
    
            const plane2 = plane0.clone();
            plane2.rotation.z = (Math.PI * 8 / 36) * 3;
            plane2.position.set(unitX - 16, -unitY + 12, 0);
            group.add(plane2);
    
            const plane3 = plane0.clone();
            plane3.rotation.z = Math.PI * 5 / 36;
            plane3.position.set(-unitX + 10, -unitY + 18, 0);
            group.add(plane3);
    
            plane0.rotation.z = -Math.PI * 12 / 36;
            plane0.position.set(-unitX + 18, unitY - 10, 0);
            resolve(true);
          });
        }),
        new Promise((resolve) => {
          loader.load(frame1, (texture) => {
            textures.push(texture);
            resolve(true);
          });
        }),
        new Promise((resolve) => {
          loader.load(frame2, (texture) => {
            textures.push(texture);
            resolve(true);
          });
        }),
        new Promise((resolve) => {
          loader.load(frame3, (texture) => {
            textures.push(texture);
            resolve(true);
          });
        }),
      ])
        .then(() => {
          scene.add(group);
          // 动画循环
          let frameIndex = 0;
          setInterval(() => {
            // 更新纹理
            group.children.forEach((plane) => {
              plane.material.map = textures[frameIndex];
            });
            // 更新帧索引
            frameIndex = (frameIndex + 1) % 4;
            // 渲染场景
            renderer.render(scene, camera);
          }, 100);
        })
        .catch((error) => {
          console.error("One of the promises rejected:", error);
        });
    };
    const setFireScale = (index, scaleX = 1, scaleY = 1) => {
      group.children.forEach((plane, i) => {
        console.log(plane, i);
        if (index === i) plane.scale.set(scaleX*2, scaleY*1.8)
      })
    };
  </script>
  
  
  <style lang="css" scoped>
  .hjm_wd_block span{
    color: white;
    /* border-bottom: 1px solid white; */
    
  }

  #huoYanDiv:deep(>canvas) {
    border-radius: 46px;
  }

  </style>
  